package com.syf.kit.core.dao.impl;

import com.syf.kit.cont.RdsDSCont;
import com.syf.kit.core.dao.SyfRdsDaoUtil;
import com.syf.kit.core.dao.mapper.MapperType;
import com.syf.kit.core.ds.impl.SyfDataSource;
import com.syf.kit.enums.DataSourceType;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;
import org.assertj.core.util.Lists;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class SyfRWRdsDaoUtilFactory extends SingleRdsDaoUtilsFactory {

    public SyfRWRdsDaoUtilFactory(SyfDataSource syfDataSource, boolean autocommit, MapperType mapperType) {
        super(syfDataSource, autocommit, mapperType);
    }

    public SyfRWRdsDaoUtilFactory(SyfDataSource syfDataSource, TransactionFactory dbTxFactory, boolean autocommit, MapperType mapperType) {
        super(syfDataSource, dbTxFactory, autocommit, mapperType);
    }

    @Override
    public SyfRdsDaoUtil buildSyfRdsDaoUtil() {
        return new SyfRWRdsDaoUtil(getSqlSessionFactory(), getMapperRegistry(), isAutoCommit(), getMapperType());
    }

    @Override
    public DataSource covertDbDataSource(SyfDataSource syfDataSource) {
        if (!DataSourceType.RW.equals(syfDataSource.getDsType())) {
            throw new RuntimeException("非法调用，此处必须传入：SyfRWDataSource");
        }

        Map<String, DataSource> dsMap = new HashMap<>();
        dsMap.put(RdsDSCont.ONLY_READ_DS_NAME, syfDataSource.getDataSourceByName(RdsDSCont.ONLY_READ_DS_NAME));
        dsMap.put(RdsDSCont.RW_DS_NAME, syfDataSource.getDataSourceByName(RdsDSCont.RW_DS_NAME));
        MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration(DataSourceType.RW.getName(), RdsDSCont.RW_DS_NAME, Lists.list(RdsDSCont.ONLY_READ_DS_NAME));
        try {
            return MasterSlaveDataSourceFactory.createDataSource(dsMap, masterSlaveRuleConfig, new Properties());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
